/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 * Description: 耗时检测工具类
 * Author: Huawei Technologies Co.
 * Create: 2022-1-14
 */

#include <chrono>
#include <iostream>
#include <string>
#include <functional>

#ifndef PENSPEEDDEMO_SCOPEDTIMECOSTREPORTER_H
#define PENSPEEDDEMO_SCOPEDTIMECOSTREPORTER_H
class ScopedTimeCostReporter {
public:
    using CallBackType = std::function<void(const char*, std::chrono::microseconds)>;

    explicit ScopedTimeCostReporter(const char* procedureName) : mProcedureName(procedureName)
    {
        mStartPoint = std::chrono::high_resolution_clock::now();
    }

    ScopedTimeCostReporter(const char* procedureName, const CallBackType& callBack)
        : mCallBack(callBack),
          mProcedureName(procedureName)
    {
        mStartPoint = std::chrono::high_resolution_clock::now();
    }

    ~ScopedTimeCostReporter()
    {
        auto timeCostNs = std::chrono::high_resolution_clock::now() - mStartPoint; // 纳秒 ns
        auto timeCostUs = std::chrono::duration_cast<std::chrono::microseconds>(timeCostNs); // 微秒 us
        if (mCallBack != nullptr) {
            mCallBack(mProcedureName, timeCostUs);
        } else {
            printf("%s cost: %llu us\n", mProcedureName, timeCostUs.count());
        }
    }
private:
    const char* mProcedureName;
    std::chrono::time_point<std::chrono::high_resolution_clock, std::chrono::nanoseconds> mStartPoint;
    CallBackType mCallBack = nullptr;
};
#endif // PENSPEEDDEMO_SCOPEDTIMECOSTREPORTER_H
